const express = require('express')
const app = express()
const { getIP, createLog, spawnChild } = require('./utils')
const auth = require('./middlewares/auth')
const access = require('./middlewares/access')

const log = createLog('app')

let isBuilding = false
let isMerging = false
let currentUser = ''

app.use(express.urlencoded({extended: true}))
app.use(express.json())
app.use(express.static('public'))
app.use(access)
app.use(auth)

function buildingTips() {
  return `<div class=warning-tips><em> ${currentUser} </em> 正在构建中，请稍候...`
}
function mergingTips() {
  return `<div class=warning-tips><em> ${currentUser} </em> 正在合并中，请稍候...`
}

function compactData(dataStr) {
  const lnSep = dataStr.includes('\r\n') ? '\r\n' : '\n'
  let lines = dataStr.split(lnSep)
  lines = lines.map(line => {
    if (line.includes('[useRouterPlugin]')) {
      line = line.replace(`D:\\bgy\\projects\\group-integrationiplatform-frontend\\projects`, '')
    } else if (line.includes('::v-deep usage')) {
      line = 'Use :deep(<inner-selector>) instead'
    }
    return line
  })
  return lines.join(lnSep)
}

app.get('/hi', (req, res) => {
  res.end('<h1>hi,' + new Date() + '</h1>')
})


app.post('/merge', (req, res) => {
  console.log('req.query', req.query)
  console.log('req.body', req.body)
  let { nickname, branch } = req.body
  if (!branch || !(branch + '').trim()) {
    branch = 'noneed'
  }

  res.setHeader('content-type', 'text/html; charset=utf-8')
  if (isBuilding) {
    res.write(buildingTips())
    spawnChild('bash', ['./scripts/log.sh'], data => {
      res.write(data)
    }, data => { res.write(data); res.end()})
    return
  }

  if (isMerging) {
    res.write(mergingTips())
    spawnChild('bash', ['./scripts/log.sh'], data => res.write(data), data => { res.write(data); res.end()})
    return
  }

  isMerging = true
  currentUser = nickname
  res.setHeader('content-type', 'text/html; charset=utf-8')

  const dataCb = (data) => {
    data = compactData(data)
    res.write(data)
  }

  const doneCb = (data) => {
    res.write(data)
    res.end()
    isMerging = false
  }

  // spawnChild('ping', ['-n', '10', 'www.baidu.com'], dataCb, doneCb)
  spawnChild('bash', ['./scripts/merge.sh', branch, nickname], dataCb, doneCb)

  // res.end('new day')
})


app.post('/build', (req, res) => {
  log('req.query', req.query)
  log('req.body', req.body)
  let { nickname, branch, pkg = 'srm' } = req.body
  if (!branch || !(branch + '').trim()) {
    branch = 'noneed'
  }

  if (isBuilding) {
    res.write(buildingTips())
    spawnChild('bash', ['./scripts/log.sh'], data => res.write(data), data => { res.write(data); res.end()})
    return
  }

  
  if (isMerging) {
    res.write(mergingTips())
    spawnChild('bash', ['./scripts/log.sh'], data => res.write(data), data => { res.write(data); res.end()})
    // res.end()
    return
  }

  isBuilding = true
  currentUser = nickname
  res.setHeader('content-type', 'text/html; charset=utf-8')

  const dataCb = (data) => {
    data = compactData(data)
    res.write(data)
  }

  const doneCb = (data) => {
    res.write(data)
    res.end()
    isBuilding = false
  }

  const getScriptName = () => {
    const env = req.query.prod ? 'prod' : req.query.uat ? 'uat' : 'sit'

    const scriptName = `build-${pkg}-${env}.sh`
    return scriptName
  }

  // spawnChild('ping', ['-n', '10', 'www.baidu.com'], dataCb, doneCb)
  spawnChild('bash', [`./scripts/${getScriptName()}`, branch, nickname], dataCb, doneCb)

  // res.end('new day')
})
app.use((req, res, next) => {
  console.log('cors middleware: ', req.url)
  res.set('Access-Control-Allow-Origin', 'http://localhost:9527')
  res.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT,HEAD')
  res.set('Access-Control-Allow-Headers', 'X-KK,Content-Type,Content-Length,Cache-Control,Date,authorization')
  next()
})

app.listen(3000, () => {
  console.log(`server in running at  http://${getIP()}:3000`);
})